<template>
  <div>
    <div class="mb-3">
      <el-button v-show="!onFile" type="primary" @click="edit()">增加股东信息</el-button>
      <el-button v-if="!onFile" type="primary" @click="dialogImportVisible = true">
        <i class="fa fa-fw fa-upload"></i>
        导入股东信息
      </el-button>
    </div>
    <loading-wrap>
      <el-table border :data="tableData" :row-class-name="tableRowClassName">
        <el-table-column align="center" label="名称" prop="real_name">
          <template slot-scope="scope">
            {{ scope.row.real_name }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="身份证/统一社会信用代码" prop="id_card">
          <template slot-scope="scope">
            {{ scope.row.id_card }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="类型" prop="is_corp">
          <template slot-scope="scope">
            {{ enumCorpType[scope.row.is_corp] || '-' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="出资方式" prop="invest_method">
          <template slot-scope="scope">
            {{ scope.row.invest_method || '-' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="认缴出资额">
          <template slot-scope="scope">
            <span>{{ scope.row.invest_funds | pureUnit('万元') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="持股比例">
          <template slot-scope="scope">
            <span>{{ scope.row.sh_rate | pureUnit('%') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="缴付期限">
          <template slot-scope="scope">
            <span v-if="scope.row.invest_rate">
              {{ $utils.dateFormat(scope.row.invest_rate, 'yyyy.MM') }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <!--编辑-->
            <el-button
              v-if="scope.row.submit_type !== '1' && !onFile"
              class="py-0 px-1"
              type="text"
              @click="edit(scope.row)"
            >
              <i class="fa fa-edit"></i>
            </el-button>
            <!--教育经历工作经历-->
            <el-tooltip class="item" content="简历及资产情况" effect="dark" placement="top-start">
              <el-button
                v-if="scope.row.is_corp !== '4'"
                class="py-0 px-1"
                type="text"
                @click="editEducation(scope.row)"
              >
                <i class="fa fa-mortar-board"></i>
              </el-button>
            </el-tooltip>
            <!--删除-->
            <el-button
              v-if="scope.row.submit_type !== '1' && !onFile"
              class="py-0 px-1 text-danger"
              type="text"
              @click="deleteData(scope.row)"
            >
              <i class="fa fa-trash"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog
        append-to-body
        :title="`${sholderName}受教育经历和工作经历`"
        top="30px"
        width="62%"
        :close-on-click-modal="false"
        :before-close="closeTable"
        :visible.sync="showTable"
      >
        <div class="d-flex align-items-center justify-content-between mb-2">
          <h5>受教育经历</h5>
          <button v-if="!onFile" class="btn btn-sm btn-primary" @click="editEdu()">
            <i class="fa fa-edit"></i>
            添加受教育经历
          </button>
        </div>

        <el-table border class="mb-3" :data="educationData">
          <el-table-column align="center" label="起止时间" width="180">
            <template slot-scope="scope">
              {{ scope.row.start_date }}~{{ scope.row.end_date }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="年龄阶段" prop="age_inter"></el-table-column>
          <el-table-column align="center" label="教育机构" prop="education_mech"></el-table-column>
          <el-table-column align="center" label="专业" prop="profession"></el-table-column>
          <el-table-column align="center" label="备注" prop="remark"></el-table-column>
          <el-table-column v-if="!onFile" align="center" label="操作">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.submit_type !== '1'"
                class="py-0 px-2"
                type="text"
                @click="editEdu(scope.row)"
              >
                <i class="fa fa-edit"></i>
              </el-button>
              <el-button
                v-if="scope.row.submit_type !== '1'"
                class="py-0 px-2 text-danger"
                type="text"
                @click="deleteData(scope.row, 'education')"
              >
                <i class="fa fa-trash"></i>
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="d-flex align-items-center justify-content-between my-2">
          <h5>工作经历</h5>
          <button v-if="!onFile" class="btn btn-sm btn-primary" @click="editWork()">
            <i class="fa fa-edit"></i>
            添加工作经历
          </button>
        </div>

        <el-table border :data="workData">
          <el-table-column align="center" label="起止时间" width="180">
            <template slot-scope="scope">
              {{ scope.row.start_date }}~{{ scope.row.end_date }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="年龄阶段" prop="age_inter"></el-table-column>
          <el-table-column align="center" label="工作单位" prop="work_unit"></el-table-column>
          <el-table-column align="center" label="职务" prop="job"></el-table-column>
          <el-table-column align="center" label="资产累积" prop="assets_total"></el-table-column>
          <el-table-column align="center" label="大额开支" prop="large_exp"></el-table-column>
          <el-table-column v-if="!onFile" align="center" label="操作">
            <template slot-scope="scope">
              <el-button class="py-0 px-2" type="text" @click="editWork(scope.row)">
                <i class="fa fa-edit"></i>
              </el-button>
              <el-button
                class="py-0 px-2 text-danger"
                type="text"
                @click="deleteData(scope.row, 'workData')"
              >
                <i class="fa fa-trash"></i>
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="d-flex align-items-center justify-content-between my-2">
          <h5>资产情况</h5>
          <button v-if="!onFile" class="btn btn-sm btn-primary" @click="editassets()">
            <i class="fa fa-edit"></i>
            编辑资产情况
          </button>
        </div>
        <el-input
          placeholder="暂无记录"
          type="textarea"
          v-model="assetsData.remark"
          :disabled="true"
          :rows="5"
        ></el-input>
      </el-dialog>
    </loading-wrap>

    <form-component
      :auto-init="false"
      :form-data="spouseData"
      :table-data="editspouseData"
      :table-id="tableId"
      :table-name="tableName"
      :visible.sync="editPersonVisible"
      @success="getData"
    ></form-component>

    <form-component
      ref="fc"
      :auto-init="false"
      :before-save="JustOne"
      :form-data="formData"
      :table-data="editData"
      :table-id="tableId"
      :table-name="tableName"
      :visible.sync="editVisible"
      @success="getData"
    ></form-component>
    <el-dialog
      append-to-body
      title="个人资产情况"
      :close-on-click-modal="false"
      :before-close="assetsClose"
      :visible.sync="assetsVisible"
    >
      <el-input
        placeholder="请输入资产信息"
        type="textarea"
        v-model="assetsRemark"
        :rows="5"
      ></el-input>
      <el-button class="btn-long" style="margin-top: 2rem" type="primary" @click="saveAssets">
        保存
      </el-button>
    </el-dialog>
    <el-dialog
      append-to-body
      title="受教育经历"
      :close-on-click-modal="false"
      :before-close="beforeEduClose"
      :visible.sync="eduVisible"
    >
      <el-form label-width="100px" :model="eduForm">
        <el-form-item label="起始时间">
          <el-date-picker
            v-model="eduForm.start_date"
            class="form-control-ml"
            placeholder="选择日期"
            style="width: 360px"
            type="month"
            value-format="yyyy-MM"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="结束时间">
          <div class="d-flex">
            <el-date-picker
              v-model="eduForm.end_date"
              class="form-control-ml mr-3"
              placeholder="选择日期"
              style="width: 360px"
              type="month"
              value-format="yyyy-MM"
              @change="onEduEndDatePicker"
            ></el-date-picker>
            <el-checkbox v-model="eduEndDate" @change="onEduEndDateChange">
              {{ eduEndDateStr }}
            </el-checkbox>
          </div>
        </el-form-item>

        <el-form-item label="教育机构">
          <el-input v-model="eduForm.education_mech" class="form-control-ml"></el-input>
        </el-form-item>

        <el-form-item label="专业">
          <el-input v-model="eduForm.profession" class="form-control-ml"></el-input>
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="eduForm.remark" class="form-control-ml"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button class="btn-long" type="primary" @click="saveEdu()">
            {{ eduId ? '修改' : '添加' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
      append-to-body
      title="工作经历"
      :close-on-click-modal="false"
      :before-close="beforeWorkClose"
      :visible.sync="workVisible"
    >
      <el-form label-width="100px" :model="workForm">
        <el-form-item label="起始时间">
          <el-date-picker
            v-model="workForm.start_date"
            class="form-control-ml"
            placeholder="选择日期"
            style="width: 360px"
            type="month"
            value-format="yyyy-MM"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="结束时间">
          <div class="d-flex">
            <el-date-picker
              v-model="workForm.end_date"
              class="form-control-ml mr-3"
              placeholder="选择日期"
              style="width: 360px"
              type="month"
              value-format="yyyy-MM"
              @change="onWorkEndDatePicker"
            ></el-date-picker>
            <el-checkbox v-model="workEndDate" @change="onWorkEndDateChange">
              {{ workEndDateStr }}
            </el-checkbox>
          </div>
        </el-form-item>

        <el-form-item label="工作单位">
          <el-input v-model="workForm.work_unit" class="form-control-ml"></el-input>
        </el-form-item>

        <el-form-item label="职务">
          <el-input v-model="workForm.job" class="form-control-ml"></el-input>
        </el-form-item>

        <el-form-item label="资产累积">
          <el-input v-model="workForm.assets_total" class="form-control-ml"></el-input>
        </el-form-item>

        <el-form-item label="大额开支">
          <el-input v-model="workForm.large_exp" class="form-control-ml"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button class="btn-long" type="primary" @click="saveWork()">
            {{ workId ? '修改' : '添加' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <import-excel
      :visible.sync="dialogImportVisible"
      title="导入股东信息"
      :post-api="postUrl"
      excel-template="/static/files/股东信息导入模板.xlsx"
      @success="handleImportSucess"
    ></import-excel>
  </div>
</template>
<script>
import FormComponent from '@/components/FormComponent'
import SelectAddress from '@/components/select/SelectAddress'
import {
  enumCorpType,
  enumEduType,
  enumMainType,
  enumMarrType,
  enumSexType,
} from '@/credit/plugins/enum'
import { PATTERN_REGISTER_NO, PATTERN_ID_CARD } from '@/common/plugins/constant'
import ImportExcel from '@/components/ImportExcel'
export default {
  components: {
    FormComponent,
    ImportExcel,
  },
  props: {},
  data() {
    return {
      postUrl: '',
      dialogImportVisible: false,
      tableData: [],
      editVisible: false,
      editPersonVisible: false,
      sholderName: '',
      showTable: false,
      assetsVisible: false,
      assetsData: {},
      assetsRemark: '',
      enumCorpType,
      enumSexType,
      enumMainType,
      enumEduType,
      enumMarrType,
      postTabelName: '',
      controller: '',
      tableName: 'datum_customer_shareholder',
      formData: {
        is_corp: {
          type: 'radio',
          label: '类型',
          hide: false,
          value: 3,
          inline: true,
          enumType: {
            3: '股东(自然人)',
            4: '股东(企业)',
            5: '非股东',
          },
          required: true,
          onClick: (v, form) => {
            v = +v
            const type = v === 4
            const ref = this.$refs.fc
            ref.setKey('sex', 'hide', type)
            ref.setKey('address_code', 'hide', type)
            ref.setKey('address_detail', 'hide', type)
            ref.setKey('exp_years', 'hide', type)
            ref.setKey('mobile_no', 'hide', type)
            ref.setKey('positio', 'hide', type)
            ref.setKey('education', 'hide', type)
            ref.setKey('marriage_status', 'hide', type)

            if (type) {
              ref.setKey('id_card', 'label', '统一社会信用代码')
              ref.setKey(
                'id_card',
                'attrs',
                Object.assign({}, (form && form.id_card && form.id_card.attrs) || {}, {
                  pattern: PATTERN_REGISTER_NO,
                })
              )
              ref.setKey('marriage_status', 'value', 0)
            } else {
              ref.setKey('id_card', 'label', '身份证号')
              ref.setKey(
                'id_card',
                'attrs',
                Object.assign({}, (form && form.id_card && form.id_card.attrs) || {}, {
                  pattern: PATTERN_ID_CARD,
                })
              )
              ref.setKey('marriage_status', 'value', 1)
            }

            const corpType = v === 4
            ref.setKey('spouse_real_name', 'hide', corpType)
            ref.setKey('spouse_sex', 'hide', corpType)
            ref.setKey('spouse_id_card', 'hide', corpType)
            ref.setKey('spouse_education', 'hide', corpType)
            ref.setKey('spouse_occupation', 'hide', corpType)
            ref.setKey('spouse_positio', 'hide', corpType)
            ref.setKey('spouse_mobile_no', 'hide', corpType)
            ref.setKey('spouse_address', 'hide', corpType)
            ref.setKey('month_income', 'hide', corpType)
            // ref.setKey('id_card', 'validator', 'false')
          },
        },
        is_actual_controller: {
          type: 'radio',
          label: '实际控制人',
          value: '0',
          inline: true,
          enumType: enumMainType,
          required: true,
          onClick: v => {
            this.controller = v
          },
        },
        real_name: { type: 'text', label: '名称', value: '', required: true },
        sex: {
          type: 'radio',
          label: '性别',
          value: '1',
          inline: true,
          enumType: enumSexType,
          required: true,
        },
        id_card: {
          type: 'text',
          label: '身份证号',
          value: '',
          required: true,
          validator: 'idCard',
        },
        marriage_status: {
          type: 'radio',
          label: '家庭状况',
          value: '1',
          enumType: enumMarrType,
          required: true,
          onClick: (v, form) => {
            const type = form.is_corp.value === '4' || v === '4' || v === '5' || v === '6'
            const ref = this.$refs.fc
            ref.setKey('spouse_real_name', 'hide', type)
            ref.setKey('spouse_sex', 'hide', type)
            ref.setKey('spouse_id_card', 'hide', type)
            ref.setKey('spouse_education', 'hide', type)
            ref.setKey('spouse_occupation', 'hide', type)
            ref.setKey('spouse_positio', 'hide', type)
            ref.setKey('spouse_mobile_no', 'hide', type)
            ref.setKey('spouse_address', 'hide', type)
            ref.setKey('month_income', 'hide', type)
            ref.setKey('spouse_real_name', 'required', !type)
          },
        },
        mobile_no: { type: 'text', label: '联系电话', value: '', validator: 'phone' },
        address_code: {
          type: 'component',
          label: '身份证所在地',
          value: '',
          component: SelectAddress,
          attrs: { class: 'form-control-ml' },
        },
        address_detail: { type: 'text', label: '现居住地址', value: '' },
        exp_years: { type: 'number', label: '从业年限', value: '', step: 1 },
        positio: { type: 'text', label: '职位', value: '' },
        education: {
          type: 'radio',
          label: '学历',
          value: '0',
          inline: true,
          enumType: enumEduType,
        },
        invest_method: { type: 'text', label: '出资方式', value: '' },
        sh_rate: { type: 'number', label: '股权比例', value: '', step: 0.01, unit: ' %', max: 100 },
        invest_funds: { type: 'number', label: '认缴出资额', value: '', unit: '万元', step: 0.01 },
        invest_rate: { type: 'date', label: '缴付期限', value: '' },
        spouse_real_name: { type: 'text', label: '配偶姓名', value: '', required: true },
        spouse_sex: {
          type: 'radio',
          label: '性别',
          value: '2',
          inline: true,
          enumType: enumSexType,
        },
        spouse_id_card: { type: 'text', label: '身份证号码', value: '' },
        spouse_mobile_no: { type: 'text', label: '配偶手机号', value: '' },
        spouse_address: { type: 'text', label: '配偶身份证地址', value: '' },
        month_income: { type: 'number', label: '月收入', value: '', unit: '元', step: 0.01 },
        spouse_education: {
          type: 'radio',
          label: '学历',
          value: '0',
          inline: true,
          enumType: enumEduType,
        },
        spouse_occupation: { type: 'text', label: '职业', value: '' },
        spouse_positio: { type: 'text', label: '职称及资质', value: '' },
      },
      postData: {},
      tableId: '',
      personId: '',
      editData: {},
      educationData: [],
      workData: [],
      //
      customerData: {},
      // 受教育经历
      eduVisible: false,
      eduId: '', // 添加
      eduForm: {},
      eduEndDate: false, // 是否是“至今”
      eduEndDateStr: '至今',
      eduLastEndDate: '', // 上次选择的结束日期
      // 工作经历
      workVisible: false,
      workId: '', // 添加
      workForm: {},
      workEndDate: false, // 是否是“至今”
      workEndDateStr: '至今',
      workLastEndDate: '', // 上次选择的结束日期,
      rowClass: true,
      spouseData: {
        real_name: { type: 'text', label: '名称', value: '', required: true },
        sex: {
          type: 'radio',
          label: '性别',
          value: '1',
          inline: true,
          enumType: enumSexType,
          required: true,
        },
        id_card: {
          type: 'text',
          label: '身份证号',
          value: '',
          required: true,
          validator: 'idCard',
        },
        // address_code: { type: 'component', label: '身份证所在地', value: '', component: SelectAddress },
        address_detail: { type: 'text', label: '身份证地址', value: '' },
        exp_years: { type: 'number', label: '从业年限', value: '', step: 1 },
        mobile_no: { type: 'text', label: '联系电话', value: '', validator: 'phone' },
        month_income: { type: 'number', label: '月收入', value: '', unit: '元', step: 0.01 },
        positio: { type: 'text', label: '职位', value: '' },
        education: {
          type: 'radio',
          label: '学历',
          value: '0',
          inline: true,
          enumType: enumEduType,
        },
        invest_method: { type: 'text', label: '出资方式', value: '' },
        sh_rate: { type: 'number', label: '股权比例', value: '', step: 0.01, unit: ' %', max: 100 },
        invest_funds: { type: 'number', label: '认缴出资额', value: '', unit: '万元', step: 0.01 },
        invest_rate: { type: 'date', label: '缴付期限', value: '' },
      },
      editspouseData: {},
    }
  },
  computed: {
    onFile() {
      return this.customerData.project_status === '1' || this.customerData.project_status === '3'
    },
  },
  watch: {},
  created() {
    this.id = this.$route.query.id || sessionStorage.getItem('customer_related_id')
    this.postUrl =
      '/api/credit/import/?importKey=datum_customer_shareholder_template&where=' +
      encodeURIComponent(
        '"datum_customer_shareholder.service_id".eq(' + this.$store.getters.org.clientId + ')'
      ) +
      encodeURIComponent('&"datum_customer_shareholder.customer_related_id".eq(' + this.id + ')')

    this.getData()

    this.getCustomerData()
    this.initEdu()
    this.initWork()
  },
  mounted() {},
  methods: {
    tableRowClassName({ row }) {
      // if (row.is_corp !== '6') {
      //   this.rowClass = !this.rowClass
      // }
      // return this.rowClass ? 'warning-row' : 'success-row'
      return row.rowCss ? 'warning-row' : 'success-row'
    },
    saveAssets() {
      if (!this.assetsData.id) {
        this.assetsData.remark = this.assetsRemark
        this.assetsData.datum_customer_shareholder_id = this.personId
        this.assetsData.customer_related_id = this.id
        this.assetsData.assets_belong_type = '3'
        this.$api
          .addData('credit', 'datum_customer_assets', this.assetsData)
          .then(() => {
            this.$message.success('保存资产信息成功！')
            this.getAssetsData(this.personId)
            this.assetsClose()
          })
          .catch(err => {
            if (err && err.status === 403) {
              return this.$message.error('还没有给您授权，请找相关部门负责人！')
            } else {
              return this.$message.error('保存失败！请重试！')
            }
          })
      } else {
        this.$api
          .updateData('credit', 'datum_customer_assets', this.assetsData.id, {
            remark: this.assetsRemark,
          })
          .then(() => {
            this.$message.success('修改资产信息成功！')
            this.getAssetsData(this.personId)
            this.assetsClose()
          })
          .catch(() => {
            this.$message.error('修改失败！')
          })
      }
    },
    JustOne() {
      if (this.controller === '1') {
        return new Promise((resolve, reject) => {
          this.$api
            .updateDataBody(
              'credit',
              'datum_customer_shareholder',
              {
                'customer_related_id.eq': this.id,
              },
              { is_actual_controller: '0' }
            )
            .then(() => {
              resolve()
            })
            .catch(e => {
              reject(new Error(e))
            })
        })
      } else {
        return null
      }
    },
    closeTable() {
      this.showTable = false
    },
    assetsClose() {
      this.assetsVisible = false
    },
    editassets() {
      this.assetsRemark = this.assetsData.remark
      this.assetsVisible = true
    },
    editPerson(p, key) {
      this.tableId = p ? p.id : ''
      if (key === 'education') {
        this.postTabelName = 'datum_customer_hand_education'
        this.postData = {
          datum_customer_shareholder_id: {
            type: 'text',
            label: 'id',
            value: this.personId,
            hide: true,
          },
          start_date: { type: 'date', label: '起始时间', value: '' },
          end_date: { type: 'date', label: '结束时间', value: '' },
          education_mech: { type: 'text', label: '教育机构', value: '' },
          profession: { type: 'text', label: '专业', value: '' },
          remark: { type: 'text', label: '备注', value: '' },
        }
      } else {
        this.postTabelName = 'datum_customer_work_exp'
        this.postData = {
          datum_customer_shareholder_id: {
            type: 'text',
            label: 'id',
            value: this.personId,
            hide: true,
          },
          start_date: { type: 'date', label: '起始时间', value: '' },
          end_date: { type: 'date', label: '结束时间', value: '' },
          work_unit: { type: 'text', label: '工作单位', value: '' },
          job: { type: 'text', label: '职务', value: '' },
          assets_total: { type: 'text', label: '资产累积', value: '' },
          large_exp: { type: 'text', label: '大额开支', value: '' },
        }
      }
      this.editData = p || {}
    },
    getPersonData() {
      this.getEducation(this.personId)
      this.getWork(this.personId)
    },
    editEducation(val) {
      this.personId = val.datum_customer_shareholder_id
      this.sholderName = val.real_name
      this.getEducation(val.datum_customer_shareholder_id)
      this.getWork(val.datum_customer_shareholder_id)
      this.getAssetsData(this.personId)
      this.showTable = true
    },
    getEducation(sid) {
      this.educationData = []
      this.$api
        .getData(
          'credit',
          'datum_customer_hand_education',
          {
            'customer_related_id.eq': this.id,
            'datum_customer_shareholder_id.eq': sid,
          },
          { age_inter: 'asc' }
        )
        .then(res => {
          this.educationData = (res && res.data) || []
        })
    },
    getAssetsData(id) {
      this.assetsData = {}
      this.$api
        .getData('credit', 'datum_customer_assets', {
          'customer_related_id.eq': this.id,
          'datum_customer_shareholder_id.eq': id,
        })
        .then(res => {
          if (res && res.data) {
            this.assetsData = res.data[0]
          }
        })
    },
    // 导入
    handleImportSucess() {
      this.getData()
      this.dialogImportVisible = false
    },
    getWork(sid) {
      this.workData = []
      this.$api
        .getData(
          'credit',
          'datum_customer_work_exp',
          {
            'customer_related_id.eq': this.id,
            'datum_customer_shareholder_id.eq': sid,
          },
          { age_inter: 'asc' }
        )
        .then(res => {
          this.workData = (res && res.data) || []
        })
    },

    getData() {
      this.$api
        .getData(
          'credit',
          this.tableName,
          {
            'customer_related_id.eq': this.id,
            'is_corp.gt': 2,
          },
          { is_corp: 'asc', create_time: 'asc' }
        )
        .then(res => {
          let tempData = (res && res.data) || []

          // 获得每位股东的配偶，不需要循环去API请求数据，把全部数据一次性请求完，自己来循环处理
          this.tableData = []
          const tempSpouse = [...tempData] // 内层循环
          const spouseIds = [] // 配偶的ID集合
          let rowOdd = false // 各行的样式
          for (let d of tempData) {
            let hasSpouse = false
            const k = spouseIds.indexOf(d.datum_customer_shareholder_id)

            if (d > -1 || d.is_corp === '6') {
              // 默认一对一，如果数据有错，有一对多的情况，此处不需要处理
              // splice是为了提高下次indexOf效率
              spouseIds.splice(k, 1)
              //
              continue
            }

            for (let i = 0; i < tempSpouse.length; i++) {
              const s = tempSpouse[i]
              if (d.spouse_related_id === s.datum_customer_shareholder_id) {
                d.rowCss = rowOdd
                s.rowCss = rowOdd
                this.tableData.push(d) // 外层用 hasSpouse 排除
                this.tableData.push(s) // 外层用 spouseIds 排除
                hasSpouse = true
                rowOdd = !rowOdd
                spouseIds.push(s.datum_customer_shareholder_id)
                // splice是为了减少下次for循环次数
                tempSpouse.splice(i, 1)
                break
              }
            }

            if (!hasSpouse) {
              d.rowCss = rowOdd
              this.tableData.push(d) // 没有配偶的股东
              rowOdd = !rowOdd
            }
          }
        })
    },

    // async getTableData(data) {
    //   let tempData = []
    //   for (let p of data) {
    //     if (p.is_corp !== '4') {
    //       let [res] = await this.$utils.promise(this.$api.getData('credit', this.tableName, {'datum_customer_shareholder_id.eq': p.spouse_related_id}))
    //       tempData.push(p)
    //       if (res && res.data) {
    //         tempData.push(res.data[0])
    //       }
    //     } else {
    //       tempData.push(p)
    //     }
    //   }
    //   this.tableData = tempData
    // },

    edit(p) {
      if (p && p.is_corp === '6') {
        this.editPersonVisible = true
        this.tableId = p ? p.datum_customer_shareholder_id : ''
        this.editspouseData = p
        return
      }
      this.editVisible = true
      this.tableId = p ? p.datum_customer_shareholder_id : ''
      this.editData = p

      if (!p) {
        this.$nextTick(() => this.$refs.fc.setKey('address_code', 'value', ''))
      }
    },

    deleteData(item, key) {
      const h = this.$createElement
      this.$msgbox({
        title: '提示',
        message: h('span', undefined, `确定删除？`),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '删除中...'
            let res = ''
            if (key === 'workData') {
              res = await this.$utils.promise(
                this.$api.deleteData('credit', 'datum_customer_work_exp', item.id)
              )
            } else if (key === 'education') {
              res = await this.$utils.promise(
                this.$api.deleteData('credit', 'datum_customer_hand_education', item.id)
              )
            } else {
              res = await this.$utils.promise(
                this.$api.deleteData('credit', this.tableName, item.datum_customer_shareholder_id)
              )
            }
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'
            if (res) {
              this.$message.success('删除成功！')
              this.getData()
              this.getPersonData()
              done()
            } else {
              this.$message.error('删除失败，请重试！')
            }
          } else {
            done()
          }
        },
      }).catch(() => {})
    },

    // 当前项目信息
    getCustomerData() {
      try {
        this.customerData = JSON.parse(sessionStorage.getItem('customer_related_view'))
      } catch (e) {
        // console.error(e)
      }
    },

    // 受教育经历 start ============================
    editEdu(row) {
      if (row) {
        // 编辑
        this.eduId = row.id
        const data = { ...row }
        if (data.end_date === this.eduEndDateStr) {
          this.eduEndDate = true
          data.end_date = ''
        }
        Object.keys(this.eduForm).forEach(key => {
          this.eduForm[key] = data[key]
        })
      } else {
        // 添加
        this.eduForm.datum_customer_shareholder_id = this.personId
      }

      this.eduVisible = true
    },

    // 初始化受教育经历表单
    initEdu() {
      this.eduId = ''
      this.eduForm = {
        datum_customer_shareholder_id: '',
        start_date: '',
        end_date: '',
        education_mech: '',
        profession: '',
        remark: '',
      }
    },

    beforeEduClose() {
      this.initEdu()
      this.eduVisible = false
    },

    // 当选择“至今”时，结束时间表单制空，否则填充上次选择的时间
    onEduEndDateChange(val) {
      if (val) {
        this.eduLastEndDate = this.eduForm.end_date
        this.eduForm.end_date = ''
      } else {
        this.eduForm.end_date = this.eduLastEndDate
      }
    },

    // 当结束时间选择时，“至今”checkbox制为未选状态
    onEduEndDatePicker() {
      this.eduEndDate = false
    },

    saveEdu() {
      const form = {}
      Object.keys(this.eduForm).forEach(key => {
        form[key] = this.eduForm[key]
      })
      if (this.eduEndDate) {
        form.end_date = this.eduEndDateStr
      }
      form.customer_related_id = this.id
      form.customer_id = this.customerData.customer_id
      form.customer_name = this.customerData.customer_name

      if (this.eduId) {
        this.$api
          .updateData('credit', 'datum_customer_hand_education', this.eduId, form)
          .then(() => {
            this.$message.success('修改受教育经历成功！')
            this.getEducation(this.personId)
            this.beforeEduClose()
          })
          .catch(() => {
            this.$message.error('修改受教育经历失败！')
          })
      } else {
        this.$api
          .addData('credit', 'datum_customer_hand_education', form)
          .then(() => {
            this.$message.success('添加受教育经历成功！')
            this.getEducation(this.personId)
            this.beforeEduClose()
          })
          .catch(() => {
            this.$message.error('添加受教育经历失败！')
          })
      }
    },
    // 受教育经历 end ============================

    // 工作经历 start ============================
    editWork(row) {
      if (row) {
        // 编辑
        this.workId = row.id
        const data = { ...row }
        if (data.end_date === this.workEndDateStr) {
          this.workEndDate = true
          data.end_date = ''
        }
        Object.keys(this.workForm).forEach(key => {
          this.workForm[key] = data[key]
        })
      } else {
        // 添加
        this.workForm.datum_customer_shareholder_id = this.personId
      }

      this.workVisible = true
    },

    // 初始化工作经历表单
    initWork() {
      this.workId = ''
      this.workForm = {
        datum_customer_shareholder_id: '',
        start_date: '',
        end_date: '',
        work_unit: '',
        job: '',
        assets_total: '',
        large_exp: '',
      }
    },

    beforeWorkClose() {
      this.initWork()
      this.workVisible = false
    },

    // 当选择“至今”时，结束时间表单制空，否则填充上次选择的时间
    onWorkEndDateChange(val) {
      if (val) {
        this.workLastEndDate = this.workForm.end_date
        this.workForm.end_date = ''
      } else {
        this.workForm.end_date = this.workLastEndDate
      }
    },

    // 当结束时间选择时，“至今”checkbox制为未选状态
    onWorkEndDatePicker() {
      this.workEndDate = false
    },

    saveWork() {
      const form = {}
      Object.keys(this.workForm).forEach(key => {
        form[key] = this.workForm[key]
      })
      if (this.workEndDate) {
        form.end_date = this.workEndDateStr
      }
      form.customer_related_id = this.id
      form.customer_id = this.customerData.customer_id
      form.customer_name = this.customerData.customer_name

      if (this.workId) {
        this.$api
          .updateData('credit', 'datum_customer_work_exp', this.workId, form)
          .then(() => {
            this.$message.success('修改工作经历成功！')
            this.getWork(this.personId)
            this.beforeWorkClose()
          })
          .catch(() => {
            this.$message.error('修改工作经历失败！')
          })
      } else {
        this.$api
          .addData('credit', 'datum_customer_work_exp', form)
          .then(() => {
            this.$message.success('添加工作经历成功！')
            this.getWork(this.personId)
            this.beforeWorkClose()
          })
          .catch(() => {
            this.$message.error('添加工作经历失败！')
          })
      }
    },
    // 工作经历 end ============================
  },
}
</script>
<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>
